PROJET 4: Réalisez une étude de santé publique avec Python
¶
\ Realized by: Sotheara SOK\ Date: 2024-06-03\ Course: Data Analyst
Objective¶
This project aims to assist MSc students studying Data Management for Finance at Audencia in identifying the key skills they need to focus on in order to align with their desired job after completing college.
About the datasets:
- Samples : 655 jobs of which 309 are Data Analyst Intern and 346 are Finance Intern
- Period : May 2023
- Location : USA
- Source : LinkedIn
- Job Experience : Internship
Key Findings:
Data Analyst Internship:
- The essential skills for a Data Analyst Internship, listed in order of importance, are Python, Java, C, SQL, C++, Javascript, Git, Excel, Linux, and AWS.
- To excel in a Data Analyst role, students should primarily focus on developing their technical skills.
Finance Internship:
- The key skills required for a Finance Internship, ranked from most to least important, are Excel, Research, Word, Organizational, Communication, PowerPoint, Interpersonal, Flexibility, Access, and Attention to Detail.
- For students aspiring to a career in finance, it is crucial to cultivate technical proficiency in Microsoft Dynamics 365, especially in Excel, alongside honing their soft skills such as communication, flexibility, organizational abilities, and attention to detail.
- Importation des librairies et chargement des fichiers
1.1. Importation des librairies
1.2. Chargement des fichiers Excel - Analyse exploratoire des fichiers
2.1. Fichier population
2.2. Fichier disponibilité alimentaire
2.3. Fichier aide alimentaire
2.4. Fichier sous nutrition - Analyse des Données
3.1. Proportion de personnes en sous nutrition
3.2. Nombre théorique de personne qui pourrait être nourries
3.3. Nombre théorique de personne qui pourrait être nourrie avec les produits végétaux
3.4. Utilisation de la disponibilité intérieure
3.5. Utilisation des céréales
3.6. Pays avec la proportion de personnes sous-alimentée la plus forte en 2017
3.7. Pays qui ont le plus bénéficié d'aide alimentaire depuis 2013
3.8. Evolution des 5 pays qui ont le plus bénéficiés de l'aide alimentaire entre 2013 et 2016
3.9. Pays avec le moins de disponibilité par habitant
3.10. Pays avec le plus de disponibilité par habitant
3.11. Exemple de la Thaïlande pour le Manioc - Analyse complémentaires
4.1. Top 10 des pays les plus producteurs
4.2. Top 10 pays dont la production est la plus faible
4.3. 10 premiers pays exportateurs
4.4. Les 10 premiers pays importateurs - Conclusion
- References
1. Importation des librairies et chargement des fichiers¶
1.1. Importation des librairies¶
import pandas as pd
import numpy as np
import warnings
from IPython.display import HTML
warnings.filterwarnings("ignore")
pd.set_option('display.max_columns', None)
pd.options.display.float_format = '{:,.2f}'.format
1.2. Chargement des fichiers Excel¶
#Importation du fichier population.csv
population = pd.read_csv('src/main/datasets/population.csv')
#Importation du fichier dispo_alimentaire.csv
dispo_alimentaire = pd.read_csv('src/main/datasets/dispo_alimentaire.csv')
#Importation du fichier aide_alimentaire.csv
aide_alimentaire = pd.read_csv('src/main/datasets/aide_alimentaire.csv')
#Importation du fichier sous_nutrition.csv
sous_nutrition = pd.read_csv('src/main/datasets/sous_nutrition.csv')
2. Analyse exploratoire des fichiers¶
2.1. Fichier population¶
#Afficher les dimensions du dataset
print("Le tableau comporte {} observation(s) ou article(s)".format(population.shape[0]))
print("Le tableau comporte {} colonne(s)".format(population.shape[1]))
Le tableau comporte 1416 observation(s) ou article(s) Le tableau comporte 3 colonne(s)
#Consulter le nombre de colonnes
print("Le tableau comporte {} colonne(s)".format(population.shape[1]))
#La nature des données dans chacune des colonnes
print(population.dtypes)
#Le nombre de valeurs présentes dans chacune des colonnes
print(population.count())
Le tableau comporte 3 colonne(s) Zone object Année int64 Valeur float64 dtype: object Zone 1416 Année 1416 Valeur 1416 dtype: int64
#Affichage les 5 premières lignes de la table
population.head()
| Zone | Année | Valeur | |
|---|---|---|---|
| 0 | Afghanistan | 2013 | 32,269.59 |
| 1 | Afghanistan | 2014 | 33,370.79 |
| 2 | Afghanistan | 2015 | 34,413.60 |
| 3 | Afghanistan | 2016 | 35,383.03 |
| 4 | Afghanistan | 2017 | 36,296.11 |
#Nous allons harmoniser les unités. Pour cela, nous avons décidé de multiplier la population par 1000
#Multiplication de la colonne valeur par 1000
population['Valeur'] = population['Valeur']*1000
#changement du nom de la colonne Valeur par Population
population = population.rename(columns={'Valeur': 'Population'})
#Affichage les 5 premières lignes de la table pour voir les modifications
population.head()
| Zone | Année | Population | |
|---|---|---|---|
| 0 | Afghanistan | 2013 | 32,269,589.00 |
| 1 | Afghanistan | 2014 | 33,370,794.00 |
| 2 | Afghanistan | 2015 | 34,413,603.00 |
| 3 | Afghanistan | 2016 | 35,383,032.00 |
| 4 | Afghanistan | 2017 | 36,296,113.00 |
2.2. Fichier disponibilité alimentaire¶
#Afficher les dimensions du dataset
print("Le tableau comporte {} observation(s) ou article(s)".format(dispo_alimentaire.shape[0]))
Le tableau comporte 15605 observation(s) ou article(s)
#Consulter le nombre de colonnes
print("Le tableau comporte {} colonne(s)".format(dispo_alimentaire.shape[1]))
Le tableau comporte 18 colonne(s)
dispo_alimentaire.dtypes
Zone object Produit object Origine object Aliments pour animaux float64 Autres Utilisations float64 Disponibilité alimentaire (Kcal/personne/jour) float64 Disponibilité alimentaire en quantité (kg/personne/an) float64 Disponibilité de matière grasse en quantité (g/personne/jour) float64 Disponibilité de protéines en quantité (g/personne/jour) float64 Disponibilité intérieure float64 Exportations - Quantité float64 Importations - Quantité float64 Nourriture float64 Pertes float64 Production float64 Semences float64 Traitement float64 Variation de stock float64 dtype: object
#Affichage les 5 premières lignes de la table
dispo_alimentaire.head()
| Zone | Produit | Origine | Aliments pour animaux | Autres Utilisations | Disponibilité alimentaire (Kcal/personne/jour) | Disponibilité alimentaire en quantité (kg/personne/an) | Disponibilité de matière grasse en quantité (g/personne/jour) | Disponibilité de protéines en quantité (g/personne/jour) | Disponibilité intérieure | Exportations - Quantité | Importations - Quantité | Nourriture | Pertes | Production | Semences | Traitement | Variation de stock | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Afghanistan | Abats Comestible | animale | NaN | NaN | 5.00 | 1.72 | 0.20 | 0.77 | 53.00 | NaN | NaN | 53.00 | NaN | 53.00 | NaN | NaN | NaN |
| 1 | Afghanistan | Agrumes, Autres | vegetale | NaN | NaN | 1.00 | 1.29 | 0.01 | 0.02 | 41.00 | 2.00 | 40.00 | 39.00 | 2.00 | 3.00 | NaN | NaN | NaN |
| 2 | Afghanistan | Aliments pour enfants | vegetale | NaN | NaN | 1.00 | 0.06 | 0.01 | 0.03 | 2.00 | NaN | 2.00 | 2.00 | NaN | NaN | NaN | NaN | NaN |
| 3 | Afghanistan | Ananas | vegetale | NaN | NaN | 0.00 | 0.00 | NaN | NaN | 0.00 | NaN | 0.00 | 0.00 | NaN | NaN | NaN | NaN | NaN |
| 4 | Afghanistan | Bananes | vegetale | NaN | NaN | 4.00 | 2.70 | 0.02 | 0.05 | 82.00 | NaN | 82.00 | 82.00 | NaN | NaN | NaN | NaN | NaN |
#remplacement des NaN dans le dataset par des 0
dispo_alimentaire = dispo_alimentaire.fillna(0)
# multiplication de toutes les lignes contenant des milliers de tonnes en Kg
milliers_tonnes_col = [
"Aliments pour animaux",
"Autres Utilisations",
"Disponibilité intérieure",
"Exportations - Quantité",
"Importations - Quantité",
"Nourriture",
"Pertes",
"Production",
"Semences",
"Traitement",
"Variation de stock",
]
dispo_alimentaire[milliers_tonnes_col] = dispo_alimentaire[milliers_tonnes_col].apply(lambda x: x*1_000_000)
#Affichage les 5 premières lignes de la table
dispo_alimentaire.head()
| Zone | Produit | Origine | Aliments pour animaux | Autres Utilisations | Disponibilité alimentaire (Kcal/personne/jour) | Disponibilité alimentaire en quantité (kg/personne/an) | Disponibilité de matière grasse en quantité (g/personne/jour) | Disponibilité de protéines en quantité (g/personne/jour) | Disponibilité intérieure | Exportations - Quantité | Importations - Quantité | Nourriture | Pertes | Production | Semences | Traitement | Variation de stock | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Afghanistan | Abats Comestible | animale | 0.00 | 0.00 | 5.00 | 1.72 | 0.20 | 0.77 | 53,000,000.00 | 0.00 | 0.00 | 53,000,000.00 | 0.00 | 53,000,000.00 | 0.00 | 0.00 | 0.00 |
| 1 | Afghanistan | Agrumes, Autres | vegetale | 0.00 | 0.00 | 1.00 | 1.29 | 0.01 | 0.02 | 41,000,000.00 | 2,000,000.00 | 40,000,000.00 | 39,000,000.00 | 2,000,000.00 | 3,000,000.00 | 0.00 | 0.00 | 0.00 |
| 2 | Afghanistan | Aliments pour enfants | vegetale | 0.00 | 0.00 | 1.00 | 0.06 | 0.01 | 0.03 | 2,000,000.00 | 0.00 | 2,000,000.00 | 2,000,000.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 | Afghanistan | Ananas | vegetale | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| 4 | Afghanistan | Bananes | vegetale | 0.00 | 0.00 | 4.00 | 2.70 | 0.02 | 0.05 | 82,000,000.00 | 0.00 | 82,000,000.00 | 82,000,000.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
2.3. Fichier aide alimentaire¶
#Afficher les dimensions du dataset
print("Le tableau comporte {} observation(s) ou article(s)".format(aide_alimentaire.shape[0]))
Le tableau comporte 1475 observation(s) ou article(s)
#Consulter le nombre de colonnes
print("Le tableau comporte {} colonne(s)".format(aide_alimentaire.shape[1]))
Le tableau comporte 4 colonne(s)
aide_alimentaire.dtypes
Pays bénéficiaire object Année int64 Produit object Valeur int64 dtype: object
#Affichage les 5 premières lignes de la table
aide_alimentaire.head().style.format({'Valeur': "{:,}"})
| Pays bénéficiaire | Année | Produit | Valeur | |
|---|---|---|---|---|
| 0 | Afghanistan | 2013 | Autres non-céréales | 682 |
| 1 | Afghanistan | 2014 | Autres non-céréales | 335 |
| 2 | Afghanistan | 2013 | Blé et Farin | 39,224 |
| 3 | Afghanistan | 2014 | Blé et Farin | 15,160 |
| 4 | Afghanistan | 2013 | Céréales | 40,504 |
#changement du nom de la colonne Pays bénéficiaire par Zone
aide_alimentaire = aide_alimentaire.rename(columns={'Pays bénéficiaire': 'Zone'})
#Multiplication de la colonne Aide_alimentaire qui contient des tonnes par 1000 pour avoir des kg
aide_alimentaire['Valeur'] = aide_alimentaire['Valeur']*1000
#Affichage les 5 premières lignes de la table
aide_alimentaire.head().style.format({'Valeur': "{:,}"})
| Zone | Année | Produit | Valeur | |
|---|---|---|---|---|
| 0 | Afghanistan | 2013 | Autres non-céréales | 682,000 |
| 1 | Afghanistan | 2014 | Autres non-céréales | 335,000 |
| 2 | Afghanistan | 2013 | Blé et Farin | 39,224,000 |
| 3 | Afghanistan | 2014 | Blé et Farin | 15,160,000 |
| 4 | Afghanistan | 2013 | Céréales | 40,504,000 |
2.4. Fichier sous nutrition¶
#Afficher les dimensions du dataset
print("Le tableau comporte {} observation(s) ou article(s)".format(sous_nutrition.shape[0]))
Le tableau comporte 1218 observation(s) ou article(s)
#Consulter le nombre de colonnes
print("Le tableau comporte {} colonne(s)".format(sous_nutrition.shape[1]))
Le tableau comporte 3 colonne(s)
#Afficher les 5 premières lignes de la table
sous_nutrition.head()
| Zone | Année | Valeur | |
|---|---|---|---|
| 0 | Afghanistan | 2012-2014 | 8.6 |
| 1 | Afghanistan | 2013-2015 | 8.8 |
| 2 | Afghanistan | 2014-2016 | 8.9 |
| 3 | Afghanistan | 2015-2017 | 9.7 |
| 4 | Afghanistan | 2016-2018 | 10.5 |
#Conversion de la colonne (avec l'argument errors=coerce qui permet de convertir automatiquement les lignes qui ne sont pas des nombres en NaN)
#Puis remplacement des NaN en 0
sous_nutrition['Valeur'] = pd.to_numeric(sous_nutrition['Valeur'], errors='coerce')
#changement du nom de la colonne Valeur par sous_nutrition
sous_nutrition = sous_nutrition.rename(columns={'Valeur': 'Sous_nutrition'})
#Multiplication de la colonne sous_nutrition par 1000000
sous_nutrition['Sous_nutrition'] = sous_nutrition['Sous_nutrition']*1_000_000
#Afficher les 5 premières lignes de la table
sous_nutrition.head()
| Zone | Année | Sous_nutrition | |
|---|---|---|---|
| 0 | Afghanistan | 2012-2014 | 8,600,000.00 |
| 1 | Afghanistan | 2013-2015 | 8,800,000.00 |
| 2 | Afghanistan | 2014-2016 | 8,900,000.00 |
| 3 | Afghanistan | 2015-2017 | 9,700,000.00 |
| 4 | Afghanistan | 2016-2018 | 10,500,000.00 |
sous_nutrition['Année'].unique()
array(['2012-2014', '2013-2015', '2014-2016', '2015-2017', '2016-2018',
'2017-2019'], dtype=object)
3. Analyse des Données¶
3.1. Proportion de personnes en sous nutrition¶
# Il faut tout d'abord faire une jointure entre la table population et la table sous nutrition, en ciblant l'année 2017
#Jointure entre la table population et la table sous_nutrition
sous_nutrition_2017 = sous_nutrition[sous_nutrition['Année'] == '2016-2018']
population_2017 = population[population['Année'] == 2017]
population_sous_nutrition = pd.merge(population_2017, sous_nutrition_2017, on=['Zone'], how='inner').drop(columns=['Année_x', 'Année_y'])
#Affichage du dataset
population_sous_nutrition.head()
| Zone | Population | Sous_nutrition | |
|---|---|---|---|
| 0 | Afghanistan | 36,296,113.00 | 10,500,000.00 |
| 1 | Afrique du Sud | 57,009,756.00 | 3,100,000.00 |
| 2 | Albanie | 2,884,169.00 | 100,000.00 |
| 3 | Algérie | 41,389,189.00 | 1,300,000.00 |
| 4 | Allemagne | 82,658,409.00 | NaN |
#Calcul et affichage du nombre de personnes en état de sous nutrition
total_pop_2017 = np.round(population_sous_nutrition["Population"].sum())
print("{:.2} billion".format(total_pop_2017/1_000_000_000))
7.5 billion
total_sous_nutri_2017 = np.round(population_sous_nutrition["Sous_nutrition"].sum())
print("{:} million".format(total_sous_nutri_2017/1_000_000))
535.7 million
total_sous_nutri_2017/total_pop_2017*100
7.1011968332354165
import plotly.express as px
# import plotly.graph_objects as go
# Calculate the sum of 'Population' and 'Sous_nutrition'
df_sum = population_sous_nutrition[["Population", "Sous_nutrition"]].sum()
# Calculate the rates
sous_nutrition_rate = df_sum["Sous_nutrition"] / df_sum["Population"] * 100
sufficient_nutrition_rate = 100 - sous_nutrition_rate
# Create a new DataFrame for the pie chart
df_pie = pd.DataFrame(
{
"Nutrition": ["Undernourished", "Sufficient"],
"Rate": [sous_nutrition_rate, sufficient_nutrition_rate],
}
)
# Create the pie chart
fig = px.pie(
df_pie,
values="Rate",
names="Nutrition",
title="Nutrition Status in 2017",
hole=0.3,
color_discrete_sequence=["blue", "red"],
)
fig.update_traces(textinfo="percent+label", pull=[0.1, 0], rotation=100)
fig.update_layout(
width=800,
height=600,
annotations=[dict(text="Total Pop:<br> 7.5 Billion", showarrow=False)],
showlegend=False,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white"),
)
fig.show()
fig.write_image("src/main/extracted_data/1.svg")
3.2. Nombre théorique de personne qui pourrait être nourries¶
#Combien mange en moyenne un être humain ? Source =>
#https://news.yahoo.com/much-humans-eat-numerical-breakdown-181300224.html?guccounter=1&guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&guce_referrer_sig=AQAAALuJLrq4oPbwdPeKjMaGFqf8V-FPJbitkK6vIelD5UPvwQ1cx49nEXskW0-rkspJQHGFC61zncCC1Wa9yWOxEQMA01AEMa5OBdqXXInw25U7ZLMb9LsnU5nyBd1en8dvibMuDWEVtE_c2XghW-x_OwFjpSFgxQQTXFARYQDlWNPI
#On commence par faire une jointure entre le data frame population et Dispo_alimentaire afin d'ajouter dans ce dernier la population
#de chaque pays
population_2017 = population[population['Année'] == 2017]
dispo_alimentaire = pd.merge(dispo_alimentaire, population_2017[['Zone', 'Population']], on='Zone')
#Affichage du nouveau dataframe
dispo_alimentaire.head()
| Zone | Produit | Origine | Aliments pour animaux | Autres Utilisations | Disponibilité alimentaire (Kcal/personne/jour) | Disponibilité alimentaire en quantité (kg/personne/an) | Disponibilité de matière grasse en quantité (g/personne/jour) | Disponibilité de protéines en quantité (g/personne/jour) | Disponibilité intérieure | Exportations - Quantité | Importations - Quantité | Nourriture | Pertes | Production | Semences | Traitement | Variation de stock | Population | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Afghanistan | Abats Comestible | animale | 0.00 | 0.00 | 5.00 | 1.72 | 0.20 | 0.77 | 53,000,000.00 | 0.00 | 0.00 | 53,000,000.00 | 0.00 | 53,000,000.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 |
| 1 | Afghanistan | Agrumes, Autres | vegetale | 0.00 | 0.00 | 1.00 | 1.29 | 0.01 | 0.02 | 41,000,000.00 | 2,000,000.00 | 40,000,000.00 | 39,000,000.00 | 2,000,000.00 | 3,000,000.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 |
| 2 | Afghanistan | Aliments pour enfants | vegetale | 0.00 | 0.00 | 1.00 | 0.06 | 0.01 | 0.03 | 2,000,000.00 | 0.00 | 2,000,000.00 | 2,000,000.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 |
| 3 | Afghanistan | Ananas | vegetale | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 |
| 4 | Afghanistan | Bananes | vegetale | 0.00 | 0.00 | 4.00 | 2.70 | 0.02 | 0.05 | 82,000,000.00 | 0.00 | 82,000,000.00 | 82,000,000.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 |
# Calcul du nombre d'humains pouvant être nourris
dispo_alimentaire["Disponibilité alimentaire en million (Kcal/jour)"] = np.round(
(
dispo_alimentaire["Disponibilité alimentaire (Kcal/personne/jour)"]
* dispo_alimentaire["Population"]
),
2,
)
total_dispo_alimentaire = np.round(
dispo_alimentaire["Disponibilité alimentaire en million (Kcal/jour)"].sum()
)
humain_pouvant_nourris = total_dispo_alimentaire / 2250
print("{:.2} billion".format(humain_pouvant_nourris / 1_000_000_000))
9.3 billion
humain_pouvant_nourris/total_pop_2017*100
123.24462480252483
import plotly.graph_objects as go
# Data
population = population_2017["Population"].sum()
capacity = humain_pouvant_nourris
population_percent = 100
capacity_percent = capacity / population * 100
# Create a bar chart using Plotly
fig = go.Figure(
data=[
go.Bar(
name="Population",
x=["Population"],
y=[population],
marker_color="blue",
text=[f"{population_percent:.0f}%"],
textposition="outside",
),
go.Bar(
name="Capacité d'alimentation",
x=["Capacité d'alimentation"],
y=[capacity],
marker_color="green",
text=[f"{capacity_percent:.0f}%"],
textposition="outside",
),
]
)
# Update the layout
fig.update_layout(
title="Population vs Capacité d'alimentation",
yaxis_title="Population",
barmode="group",
showlegend=False,
width=800,
height=600,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
annotations=[
dict(
x="Population",
y=population / 2,
text=f"{population/1_000_000_000:.1f} Billion",
showarrow=False,
font=dict(color="white", size=30),
xanchor="center",
yanchor="middle"
),
dict(
x="Capacité d'alimentation",
y=population / 2,
text=f"{capacity/1_000_000_000:.1f} Billion",
showarrow=False,
font=dict(color="white", size=30),
xanchor="center",
yanchor="middle"
)
]
)
# Show the figure
fig.show()
fig.write_image("src/main/extracted_data/2.svg")
3.3. Nombre théorique de personne qui pourrait être nourrie avec les produits végétaux¶
#Transfert des données avec les végétaux dans un nouveau dataframe
dispo_alimentaire_vegetaux = dispo_alimentaire[dispo_alimentaire['Origine'] == 'vegetale']
# Calcul du nombre de kcal disponible pour les végétaux
dispo_alimentaire_vegetaux["dispo_kcal"] = np.round(
(
dispo_alimentaire_vegetaux["Disponibilité alimentaire (Kcal/personne/jour)"]
* dispo_alimentaire_vegetaux["Population"]
),
2,
)
total_dispo_alimentaire_vegetaux = np.round(
dispo_alimentaire_vegetaux["dispo_kcal"].sum()
)
print("{:,.2f} billion kcal".format(total_dispo_alimentaire_vegetaux / 1_000_000_000))
17,260.76 billion kcal
# Calcul du nombre d'humains pouvant être nourris avec les végétaux
humain_pouvant_nourris_vegetaux = total_dispo_alimentaire_vegetaux / 2250
print("{:.2f} billion".format(humain_pouvant_nourris_vegetaux / 1_000_000_000))
7.67 billion
humain_pouvant_nourris_vegetaux/total_pop_2017*100
101.69214457340064
# Data
population = population_2017["Population"].sum()
capacity = humain_pouvant_nourris_vegetaux
population_percent = 100
capacity_percent = capacity / population * 100
# Create a bar chart using Plotly
fig = go.Figure(
data=[
go.Bar(
name="Population",
x=["Population"],
y=[population],
marker_color="blue",
text=[f"{population_percent:.0f}%"],
textposition="outside",
),
go.Bar(
name="Capacity",
x=["Capacity"],
y=[capacity],
marker_color="green",
text=[f"{capacity_percent:.0f}%"],
textposition="outside",
),
]
)
# Update the layout
fig.update_layout(
title="Population vs Feeding Capacity by Vegetal Products",
yaxis_title="Population",
barmode="group",
showlegend=False,
width=800,
height=600,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# Add annotations one by one
fig.add_annotation(
x="Population",
y=population / 2,
text=f"{population/1_000_000_000:.1f} Billion",
showarrow=False,
font=dict(color="white", size=30),
)
fig.add_annotation(
x="Capacity",
y=population / 2,
text=f"{capacity/1_000_000_000:.1f} Billion",
showarrow=False,
font=dict(color="white", size=30),
)
# Show the figure
fig.show()
fig.write_image("src/main/extracted_data/3.svg")
3.4. Utilisation de la disponibilité intérieure¶
#Calcul de la disponibilité totale
dispo_alimentaire_total = dispo_alimentaire["Disponibilité intérieure"].sum()
print("{:,.2f} million".format(dispo_alimentaire_total/1_000_000))
9,733,927.00 million
# création d'une boucle for pour afficher les différentes valeurs en fonction des colonnes aliments pour animaux, pertes, nourritures,
columns = ["Aliments pour animaux", "Pertes", "Nourriture", "Semences", "Traitement", "Autres Utilisations"]
for col in columns:
dispo_alimentaire[col].fillna(0, inplace=True)
dispo_alimentaire_sum = dispo_alimentaire[col].sum()
dispo_alimentaire_proportion = dispo_alimentaire_sum / dispo_alimentaire_total
print(f"{col} proportion is {dispo_alimentaire_proportion*100:.2f}%")
Aliments pour animaux proportion is 13.23% Pertes proportion is 4.65% Nourriture proportion is 49.37% Semences proportion is 1.58% Traitement proportion is 22.45% Autres Utilisations proportion is 8.82%
columns
['Aliments pour animaux', 'Pertes', 'Nourriture', 'Semences', 'Traitement', 'Autres Utilisations']
df_sum = []
columns = [
"Aliments pour animaux",
"Pertes",
"Nourriture",
"Semences",
"Traitement",
"Autres Utilisations",
]
# Calculate the sum for each column and store it in the list
for col in columns:
dispo_alimentaire[col].fillna(0, inplace=True)
dispo_alimentaire_sum = dispo_alimentaire[col].sum()
df_sum.append(dispo_alimentaire_sum)
# Create the pie chart
fig = px.pie(
values=df_sum,
names=columns,
title="Breakdown of food availability in 2017",
hole=0.3,
color_discrete_sequence=["blue", "red", "yellow", "rgb(163,163,163)", "rgb(187,187,187)", "rgb(204,204,204)"],
)
fig.update_traces(textinfo="percent+label")
fig.update_layout(
width=800,
height=600,
annotations=[
dict(
text=f"Total Dispo Ali:<br> {dispo_alimentaire_total/1_000_000_000:,.0f} Billion",
showarrow=False,
)
],
showlegend=False,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=12),
)
fig.show()
fig.write_image("src/main/extracted_data/4.svg")
3.5. Utilisation des céréales¶
What is this section about???
dispo_alimentaire["Produit"].unique()
array(['Abats Comestible', 'Agrumes, Autres', 'Aliments pour enfants',
'Ananas', 'Bananes', 'Beurre, Ghee', 'Bière', 'Blé',
'Boissons Alcooliques', 'Café', 'Coco (Incl Coprah)', 'Crème',
'Céréales, Autres', 'Dattes', 'Edulcorants Autres',
'Feve de Cacao', 'Fruits, Autres', 'Graines de coton',
'Graines de tournesol', 'Graisses Animales Crue',
'Huil Plantes Oleif Autr', 'Huile Graines de Coton',
"Huile d'Arachide", "Huile d'Olive", 'Huile de Colza&Moutarde',
'Huile de Palme', 'Huile de Soja', 'Huile de Sésame',
'Huile de Tournesol', 'Lait - Excl Beurre', 'Légumes, Autres',
'Légumineuses Autres', 'Maïs', 'Miel', 'Millet', 'Miscellanees',
'Noix', 'Oeufs', 'Olives', 'Oranges, Mandarines', 'Orge',
'Plantes Oleiferes, Autre', 'Poissons Eau Douce', 'Poivre',
'Pommes', 'Pommes de Terre', 'Raisin', 'Riz (Eq Blanchi)',
'Sucre Eq Brut', 'Sucre, betterave', 'Sucre, canne', 'Sésame',
'Thé', 'Tomates', "Viande d'Ovins/Caprins", 'Viande de Bovins',
'Viande de Volailles', 'Viande, Autre', 'Vin', 'Épices, Autres',
'Alcool, non Comestible', 'Animaux Aquatiques Autre',
'Arachides Decortiquees', 'Avoine', 'Bananes plantains',
'Boissons Fermentés', 'Cephalopodes', 'Citrons & Limes',
'Crustacés', 'Girofles', 'Graines Colza/Moutarde', 'Haricots',
'Huile de Coco', 'Huile de Germe de Maïs', 'Huile de Palmistes',
'Huiles de Foie de Poisso', 'Huiles de Poissons', 'Ignames',
'Manioc', 'Mollusques, Autres', 'Oignons', 'Palmistes',
'Pamplemousse', 'Patates douces', 'Perciform', 'Piments',
'Plantes Aquatiques', 'Pois', 'Poissons Marins, Autres',
'Poissons Pelagiques', 'Racines nda', 'Seigle', 'Soja', 'Sorgho',
'Viande de Suides', 'Huile de Son de Riz', 'Sucre non centrifugé',
'Viande de Anim Aquatiq'], dtype=object)
# Création d'une liste avec toutes les variables
cereales = [
"Blé",
"Riz (Eq Blanchi)",
"Orge",
"Maïs",
"Millet",
"Seigle",
"Avoine",
"Sorgho",
"Céréales, Autres"
]
#Création d'un dataframe avec les informations uniquement pour ces céréales
dispo_alimentaire_cereales = dispo_alimentaire[dispo_alimentaire['Produit'].isin(cereales)]
dispo_alimentaire_cereales.head()
| Zone | Produit | Origine | Aliments pour animaux | Autres Utilisations | Disponibilité alimentaire (Kcal/personne/jour) | Disponibilité alimentaire en quantité (kg/personne/an) | Disponibilité de matière grasse en quantité (g/personne/jour) | Disponibilité de protéines en quantité (g/personne/jour) | Disponibilité intérieure | Exportations - Quantité | Importations - Quantité | Nourriture | Pertes | Production | Semences | Traitement | Variation de stock | Population | Disponibilité alimentaire en million (Kcal/jour) | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 7 | Afghanistan | Blé | vegetale | 0.00 | 0.00 | 1,369.00 | 160.23 | 4.69 | 36.91 | 5,992,000,000.00 | 0.00 | 1,173,000,000.00 | 4,895,000,000.00 | 775,000,000.00 | 5,169,000,000.00 | 322,000,000.00 | 0.00 | -350,000,000.00 | 36,296,113.00 | 49,689,378,697.00 |
| 12 | Afghanistan | Céréales, Autres | vegetale | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 | 0.00 |
| 32 | Afghanistan | Maïs | vegetale | 200,000,000.00 | 0.00 | 21.00 | 2.50 | 0.30 | 0.56 | 313,000,000.00 | 0.00 | 1,000,000.00 | 76,000,000.00 | 31,000,000.00 | 312,000,000.00 | 5,000,000.00 | 0.00 | 0.00 | 36,296,113.00 | 762,218,373.00 |
| 34 | Afghanistan | Millet | vegetale | 0.00 | 0.00 | 3.00 | 0.40 | 0.02 | 0.08 | 13,000,000.00 | 0.00 | 0.00 | 12,000,000.00 | 1,000,000.00 | 13,000,000.00 | 0.00 | 0.00 | 0.00 | 36,296,113.00 | 108,888,339.00 |
| 40 | Afghanistan | Orge | vegetale | 360,000,000.00 | 0.00 | 26.00 | 2.92 | 0.24 | 0.79 | 524,000,000.00 | 0.00 | 10,000,000.00 | 89,000,000.00 | 52,000,000.00 | 514,000,000.00 | 22,000,000.00 | 0.00 | 0.00 | 36,296,113.00 | 943,698,938.00 |
dispo_alimentaire_cereales["Produit"].unique()
array(['Blé', 'Céréales, Autres', 'Maïs', 'Millet', 'Orge',
'Riz (Eq Blanchi)', 'Avoine', 'Seigle', 'Sorgho'], dtype=object)
#Affichage de la proportion d'alimentation animale
dispo_alimentaire_cereales['Aliments pour animaux'].fillna(0, inplace=True)
dispo_alimentaire_cereal_total = dispo_alimentaire_cereales['Disponibilité intérieure'].sum()
dispo_alimentaire_cereales_animaux = dispo_alimentaire_cereales['Aliments pour animaux'].sum()
print("{:.2f} billion".format(dispo_alimentaire_cereales_animaux / 1_000_000_000))
859.62 billion
#Affichage de la proportion d'alimentation animale
print(f"Aliments pour animaux proportion is {dispo_alimentaire_cereales_animaux/dispo_alimentaire_cereal_total*100:.2f}%")
Aliments pour animaux proportion is 36.14%
dispo_alimentaire_celreales_nurriture = dispo_alimentaire_cereales["Nourriture"].sum()
print("{:.2f} billion".format(dispo_alimentaire_celreales_nurriture / 1_000_000_000))
1020.46 billion
print(f"Aliments pour nourriture is {dispo_alimentaire_celreales_nurriture/dispo_alimentaire_cereal_total*100:.2f}%")
Aliments pour nourriture is 42.91%
# Calculate the proportions
nourriture_prop = dispo_alimentaire_celreales_nurriture / dispo_alimentaire_cereal_total
animaux_prop = dispo_alimentaire_cereales_animaux / dispo_alimentaire_cereal_total
others = 1 - nourriture_prop - animaux_prop
# Create the data for the pie chart
values = [nourriture_prop, animaux_prop, others]
labels = ["Aliments pour nourriture", "Aliments pour animaux", "Others"]
# Create the pie chart using Plotly
fig = px.pie(values=values, names=labels, title="Breakdown of Cereal Usage", hole=0.3, color_discrete_sequence=["blue", "red", "gray"])
fig.update_traces(textinfo="percent+label", rotation=100)
fig.update_layout(
width=800,
height=600,
annotations=[
dict(
text=f"Total Dispo Cereal:<br> {dispo_alimentaire_cereal_total/1_000_000_000:,.0f} Billion",
showarrow=False,
)
],
showlegend=False,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=12),
)
# Show the figure
fig.show()
fig.write_image("src/main/extracted_data/5.svg")
3.6. Pays avec la proportion de personnes sous-alimentée la plus forte en 2017¶
population_sous_nutrition
| Zone | Population | Sous_nutrition | |
|---|---|---|---|
| 0 | Afghanistan | 36,296,113.00 | 10,500,000.00 |
| 1 | Afrique du Sud | 57,009,756.00 | 3,100,000.00 |
| 2 | Albanie | 2,884,169.00 | 100,000.00 |
| 3 | Algérie | 41,389,189.00 | 1,300,000.00 |
| 4 | Allemagne | 82,658,409.00 | NaN |
| ... | ... | ... | ... |
| 198 | Venezuela (République bolivarienne du) | 29,402,484.00 | 8,000,000.00 |
| 199 | Viet Nam | 94,600,648.00 | 6,500,000.00 |
| 200 | Yémen | 27,834,819.00 | NaN |
| 201 | Zambie | 16,853,599.00 | NaN |
| 202 | Zimbabwe | 14,236,595.00 | NaN |
203 rows × 3 columns
# Pays avec la proportion de personnes sous-alimentée la plus forte en 2017
#Création de la colonne proportion par pays
population_sous_nutrition['Proportion'] = (population_sous_nutrition['Sous_nutrition']/population_sous_nutrition['Population'])*100
#affichage après trie des 10 pires pays
population_sous_nutrition.sort_values(by='Proportion', ascending=False).head(10)
| Zone | Population | Sous_nutrition | Proportion | |
|---|---|---|---|---|
| 78 | Haïti | 10,982,366.00 | 5,300,000.00 | 48.26 |
| 157 | République populaire démocratique de Corée | 25,429,825.00 | 12,000,000.00 | 47.19 |
| 108 | Madagascar | 25,570,512.00 | 10,500,000.00 | 41.06 |
| 103 | Libéria | 4,702,226.00 | 1,800,000.00 | 38.28 |
| 100 | Lesotho | 2,091,534.00 | 800,000.00 | 38.25 |
| 183 | Tchad | 15,016,753.00 | 5,700,000.00 | 37.96 |
| 161 | Rwanda | 11,980,961.00 | 4,200,000.00 | 35.06 |
| 121 | Mozambique | 28,649,018.00 | 9,400,000.00 | 32.81 |
| 186 | Timor-Leste | 1,243,258.00 | 400,000.00 | 32.17 |
| 0 | Afghanistan | 36,296,113.00 | 10,500,000.00 | 28.93 |
# Sort the data and select the top 10 countries
top_10_countries = population_sous_nutrition.sort_values(
by="Proportion", ascending=False
).head(10)
# Create the bar chart using Plotly
fig = px.bar(
top_10_countries,
x="Proportion",
y="Zone",
orientation="h",
title="Top 10 Countries with Highest Percentage of Undernourished Population in 2017",
labels={"Proportion": "Percentage(%)", "Zone": ""},
color="Proportion",
color_continuous_scale="reds",
# color_continuous_scale=["rgb(0,0,255)", "rgb(255,0,0)"],
text=f"Proportion",
)
# Update the layout to invert the y-axis
fig.update_layout(
width=1200,
height=500,
yaxis=dict(autorange="reversed"),
coloraxis_showscale=False,
template="plotly_white",
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
fig.update_traces(texttemplate="%{text:.0f}%", textposition="outside")
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", range=[0, 55], showgrid=False)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/ht.svg",
"https://flagicons.lipis.dev/flags/4x3/kp.svg",
"https://flagicons.lipis.dev/flags/4x3/mg.svg",
"https://flagicons.lipis.dev/flags/4x3/lr.svg",
"https://flagicons.lipis.dev/flags/4x3/ls.svg",
"https://flagicons.lipis.dev/flags/4x3/td.svg",
"https://flagicons.lipis.dev/flags/4x3/rw.svg",
"https://flagicons.lipis.dev/flags/4x3/mz.svg",
"https://flagicons.lipis.dev/flags/4x3/tl.svg",
"https://flagicons.lipis.dev/flags/4x3/af.svg"
]
# Positions of the images
proportions = top_10_countries['Proportion'].tolist()
positions = [(proportions-3, i - 0.5) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=3,
sizey=3,
layer="above",
)
)
# Show the figure
fig.show()
fig.write_image("src/main/extracted_data/6.svg")
#population_sous_nutrition.sort_values(by='Sous_nutrition', ascending=False).head(10)
3.7. Pays qui ont le plus bénéficié d'aide alimentaire depuis 2013¶
#Pays qui ont le plus bénéficié d'aide alimentaire depuis 2013
#calcul du total de l'aide alimentaire par pays
aide_alimentaire_total = aide_alimentaire.groupby('Zone')['Valeur'].sum().reset_index()
#affichage après trie des 10 pays qui ont bénéficié le plus de l'aide alimentaire
aide_alimentaire_total.sort_values(by='Valeur', ascending=False).head(10).style.format({'Valeur': "{:,}"})
| Zone | Valeur | |
|---|---|---|
| 50 | République arabe syrienne | 1,858,943,000 |
| 75 | Éthiopie | 1,381,294,000 |
| 70 | Yémen | 1,206,484,000 |
| 61 | Soudan du Sud | 695,248,000 |
| 60 | Soudan | 669,784,000 |
| 30 | Kenya | 552,836,000 |
| 3 | Bangladesh | 348,188,000 |
| 59 | Somalie | 292,678,000 |
| 53 | République démocratique du Congo | 288,502,000 |
| 43 | Niger | 276,344,000 |
aide_alimentaire_total = aide_alimentaire_total.sort_values(
by="Valeur", ascending=False
).head(10)
aide_alimentaire_total['Valeur_in_billion'] = aide_alimentaire_total['Valeur'] / 1_000_000_000
# Create the bar chart using Plotly
fig = px.bar(
aide_alimentaire_total,
x="Valeur",
y="Zone",
orientation="h",
title="Top 10 Countries with Highest Amount of Aid Received Since 2013-2016",
labels={"Valeur": "Aid Received", "Zone": "Country"},
text="Valeur",
custom_data="Valeur_in_billion",
color="Valeur",
# color_continuous_scale="Blues",
color_continuous_scale=["rgb(229,229,255)", "rgb(0,0,255)"]
)
# Update the layout to invert the y-axis and remove x-axis title and color bar
fig.update_layout(
yaxis=dict(autorange="reversed", title=None),
xaxis_title="Aid Received (€)",
coloraxis_showscale=False,
width=1200,
height=500,
template="plotly_white",
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
fig.update_traces(texttemplate="€%{customdata[0]:.2f}B", textposition="outside")
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", range=[0, 2_000_000_000], showgrid=False)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/sy.svg",
"https://flagicons.lipis.dev/flags/4x3/et.svg",
"https://flagicons.lipis.dev/flags/4x3/ye.svg",
"https://flagicons.lipis.dev/flags/4x3/ss.svg",
"https://flagicons.lipis.dev/flags/4x3/sd.svg",
"https://flagicons.lipis.dev/flags/4x3/ke.svg",
"https://flagicons.lipis.dev/flags/4x3/bd.svg",
"https://flagicons.lipis.dev/flags/4x3/so.svg",
"https://flagicons.lipis.dev/flags/4x3/cg.svg",
"https://flagicons.lipis.dev/flags/4x3/ne.svg"
]
# Positions of the images
proportions = aide_alimentaire_total['Valeur'].tolist()
positions = [(proportions-100_000_000, i - 0.5) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=100_000_000,
sizey=100_000_000,
layer="above",
)
)
# Show the figure
fig.show()
fig.write_image("src/main/extracted_data/7.svg")
3.8. Evolution des 5 pays qui ont le plus bénéficiés de l'aide alimentaire entre 2013 et 2016¶
aide_alimentaire["Année"].unique()
array([2013, 2014, 2015, 2016], dtype=int64)
#Evolution des 5 pays qui ont le plus bénéficiés de l'aide alimentaire entre 2013 et 2016
#Création d'un dataframe avec la zone, l'année et l'aide alimentaire puis groupby sur zone et année
aide_alimentaire_zone = aide_alimentaire.groupby(['Zone', 'Année'])['Valeur'].sum().reset_index()
#Création d'une liste contenant les 5 pays qui ont le plus bénéficiées de l'aide alimentaire
top_5_aide_alimentaire = aide_alimentaire_total.sort_values(by='Valeur', ascending=False).head(5)['Zone'].tolist()
#On filtre sur le dataframe avec notre liste
aide_alimentaire_zone = aide_alimentaire_zone[aide_alimentaire_zone['Zone'].isin(top_5_aide_alimentaire)]
# Affichage des pays avec l'aide alimentaire par année
aide_alimentaire_zone.style.format({'Valeur': "{:,}"})
| Zone | Année | Valeur | |
|---|---|---|---|
| 157 | République arabe syrienne | 2013 | 563,566,000 |
| 158 | République arabe syrienne | 2014 | 651,870,000 |
| 159 | République arabe syrienne | 2015 | 524,949,000 |
| 160 | République arabe syrienne | 2016 | 118,558,000 |
| 189 | Soudan | 2013 | 330,230,000 |
| 190 | Soudan | 2014 | 321,904,000 |
| 191 | Soudan | 2015 | 17,650,000 |
| 192 | Soudan du Sud | 2013 | 196,330,000 |
| 193 | Soudan du Sud | 2014 | 450,610,000 |
| 194 | Soudan du Sud | 2015 | 48,308,000 |
| 214 | Yémen | 2013 | 264,764,000 |
| 215 | Yémen | 2014 | 103,840,000 |
| 216 | Yémen | 2015 | 372,306,000 |
| 217 | Yémen | 2016 | 465,574,000 |
| 225 | Éthiopie | 2013 | 591,404,000 |
| 226 | Éthiopie | 2014 | 586,624,000 |
| 227 | Éthiopie | 2015 | 203,266,000 |
# Assuming pivot_df is the DataFrame after pivot
pivot_df = aide_alimentaire_zone.pivot(index="Année", columns="Zone", values="Valeur")
title = "Aid Received Over Time"
labels = pivot_df.columns.tolist()
colors = [
"rgb(163,163,163)", # syrie
"rgb(163,163,163)", # soudan
"rgb(163,163,163)", # sudan du sud
"rgb(0,0,255)", # yemen
"rgb(163,163,163)", # ethiopia
]
mode_size = [8, 8, 8, 12, 8]
line_size = [2, 2, 2, 4, 2]
x_data = pivot_df.index
fig = go.Figure()
# Add a trace for each zone
for i, zone in enumerate(labels):
y_data = pivot_df[zone].values
fig.add_trace(
go.Scatter(
x=x_data,
y=y_data,
mode="lines",
name=zone,
line=dict(
color=colors[i % len(colors)], width=line_size[i % len(line_size)]
),
connectgaps=True,
)
)
# Endpoints
for i, zone in enumerate(labels):
y_data = pivot_df[zone].values
# Find the last valid index
last_valid_index = len(y_data) - 1
while last_valid_index >= 0 and pd.isna(y_data[last_valid_index]):
last_valid_index -= 1
# Add a marker at the last valid index
if last_valid_index >= 0:
fig.add_trace(
go.Scatter(
x=[x_data[0], x_data[last_valid_index]],
y=[y_data[0], y_data[last_valid_index]],
mode="markers",
marker=dict(
color=colors[i % len(colors)], size=mode_size[i % len(mode_size)]
),
)
)
fig.update_layout(
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor="rgb(204, 204, 204)",
linewidth=2,
ticks="outside",
tickfont=dict(
family="Arial",
size=14,
color="white",
),
tickvals=[2013, 2014, 2015, 2016],
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
showticklabels=False,
),
autosize=False,
margin=dict(
autoexpand=False,
l=200,
r=20,
t=110,
),
showlegend=False,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
annotations = []
# Adding labels
for i, zone in enumerate(labels):
y_data = pivot_df[zone].values
color = colors[i % len(colors)]
# Labeling the left side of the plot
annotations.append(
dict(
xref="paper",
x=0.05,
y=y_data[0],
xanchor="right",
yanchor="middle",
text=zone + " {}M".format(int(y_data[0] / 1_000_000)),
font=dict(family="Arial", size=16, color="white"),
showarrow=False,
)
)
# Find the last valid index
last_valid_index = len(y_data) - 1
while last_valid_index >= 0 and pd.isna(y_data[last_valid_index]):
last_valid_index -= 1
# Labeling the right side of the plot at the last valid index
if last_valid_index >= 0:
annotations.append(
dict(
xref="x",
x=x_data[last_valid_index],
y=y_data[last_valid_index],
xanchor="left",
yanchor="middle",
text="{}M".format(int(y_data[last_valid_index] / 1_000_000)),
font=dict(family="Arial", size=16, color="white"),
showarrow=False,
)
)
# Title
annotations.append(
dict(
xref="paper",
yref="paper",
x=0.0,
y=1.05,
xanchor="left",
yanchor="bottom",
text=title,
font=dict(family="Arial", size=30, color="white"),
showarrow=False,
)
)
fig.update_layout(annotations=annotations, width=1500, height=600)
fig.show()
fig.write_image("src/main/extracted_data/8.svg")
3.9. Pays avec le moins de disponibilité par habitant¶
#Calcul de la disponibilité en kcal par personne par jour par pays
dispo_alimentaire_par_pays = dispo_alimentaire.groupby('Zone')['Disponibilité alimentaire (Kcal/personne/jour)'].sum().reset_index()
#Affichage des 10 pays qui ont le moins de dispo alimentaire par personne
dispo_alimentaire_par_pays.sort_values(by='Disponibilité alimentaire (Kcal/personne/jour)').head(10)
| Zone | Disponibilité alimentaire (Kcal/personne/jour) | |
|---|---|---|
| 127 | République centrafricaine | 1,879.00 |
| 164 | Zambie | 1,924.00 |
| 91 | Madagascar | 2,056.00 |
| 0 | Afghanistan | 2,087.00 |
| 65 | Haïti | 2,089.00 |
| 132 | République populaire démocratique de Corée | 2,093.00 |
| 150 | Tchad | 2,109.00 |
| 165 | Zimbabwe | 2,113.00 |
| 114 | Ouganda | 2,126.00 |
| 152 | Timor-Leste | 2,129.00 |
# Group and sort the data
dispo_alimentaire_par_pays = dispo_alimentaire.groupby('Zone')['Disponibilité alimentaire (Kcal/personne/jour)'].sum().reset_index()
dispo_alimentaire_par_pays = dispo_alimentaire_par_pays.sort_values(by='Disponibilité alimentaire (Kcal/personne/jour)', ascending=True).head(10)
dispo_alimentaire_par_pays.set_index('Zone', inplace=True)
# Create the Plotly bar chart
fig = go.Figure(go.Bar(
x=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'],
y=dispo_alimentaire_par_pays.index,
orientation='h',
marker=dict(
color=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'],
colorscale='Reds', # Change to a continuous color scale
reversescale=True, # Add this line to reverse the color scale
# colorbar=dict(
# title='Kcal/personne/jour',
# tickvals=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)']
# )
),
text=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)']
))
fig.update_layout(
title='Top 10 Pays avec le moins de disponibilité par habitant',
xaxis_title='Disponibilité alimentaire (Kcal/personne/jour)',
yaxis_title='',
# xaxis=dict(type='log'),
yaxis=dict(autorange='reversed'), # Invert the y-axis to display the country with the highest number at the top
template='plotly_white',
width= 1500,
height= 600,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/cf.svg",
"https://flagicons.lipis.dev/flags/4x3/zm.svg",
"https://flagicons.lipis.dev/flags/4x3/mg.svg",
"https://flagicons.lipis.dev/flags/4x3/af.svg",
"https://flagicons.lipis.dev/flags/4x3/ht.svg",
"https://flagicons.lipis.dev/flags/4x3/kp.svg",
"https://flagicons.lipis.dev/flags/4x3/td.svg",
"https://flagicons.lipis.dev/flags/4x3/zw.svg",
"https://flagicons.lipis.dev/flags/4x3/ug.svg",
"https://flagicons.lipis.dev/flags/4x3/tl.svg"
]
# Positions of the images
proportions = dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'].tolist()
positions = [(proportions-100, i-0.43) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=100,
sizey=100,
layer="above",
)
)
# Format the text to be displayed directly on the bars
fig.update_traces(texttemplate='%{text:,.0f}', textposition='outside')
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", showgrid=False)
fig.show()
fig.write_image("src/main/extracted_data/9.svg")
3.10. Pays avec le plus de disponibilité par habitant¶
#Affichage des 10 pays qui ont le plus de dispo alimentaire par personne
dispo_alimentaire_par_pays.sort_values(by='Disponibilité alimentaire (Kcal/personne/jour)', ascending=False).head(10)
| Disponibilité alimentaire (Kcal/personne/jour) | |
|---|---|
| Zone | |
| Timor-Leste | 2,129.00 |
| Ouganda | 2,126.00 |
| Zimbabwe | 2,113.00 |
| Tchad | 2,109.00 |
| République populaire démocratique de Corée | 2,093.00 |
| Haïti | 2,089.00 |
| Afghanistan | 2,087.00 |
| Madagascar | 2,056.00 |
| Zambie | 1,924.00 |
| République centrafricaine | 1,879.00 |
# Group and sort the data
dispo_alimentaire_par_pays = dispo_alimentaire.groupby('Zone')['Disponibilité alimentaire (Kcal/personne/jour)'].sum().reset_index()
dispo_alimentaire_par_pays = dispo_alimentaire_par_pays.sort_values(by='Disponibilité alimentaire (Kcal/personne/jour)', ascending=False).head(10)
dispo_alimentaire_par_pays.set_index('Zone', inplace=True)
# Create the Plotly bar chart
fig = go.Figure(go.Bar(
x=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'],
y=dispo_alimentaire_par_pays.index,
orientation='h',
marker=dict(
color=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'],
# colorscale='Blues', # Change to a continuous color scale
colorscale=["rgb(229,229,255)", "rgb(0,0,255)"]
# reversescale=True, # Add this line to reverse the color scale
# colorbar=dict(
# title='Kcal/personne/jour',
# tickvals=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)']
# )
),
text=dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'],
))
fig.update_layout(
title='Top 10 Pays avec le plus de disponibilité par habitant',
xaxis_title='Disponibilité alimentaire (Kcal/personne/jour)',
yaxis_title='',
yaxis=dict(autorange='reversed'), # Invert the y-axis to display the country with the highest number at the top
template='plotly_white',
width= 1500,
height= 600,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/at.svg",
"https://flagicons.lipis.dev/flags/4x3/be.svg",
"https://flagicons.lipis.dev/flags/4x3/tr.svg",
"https://flagicons.lipis.dev/flags/4x3/us.svg",
"https://flagicons.lipis.dev/flags/4x3/il.svg",
"https://flagicons.lipis.dev/flags/4x3/ie.svg",
"https://flagicons.lipis.dev/flags/4x3/it.svg",
"https://flagicons.lipis.dev/flags/4x3/lu.svg",
"https://flagicons.lipis.dev/flags/4x3/eg.svg",
"https://flagicons.lipis.dev/flags/4x3/de.svg"
]
# Positions of the images
proportions = dispo_alimentaire_par_pays['Disponibilité alimentaire (Kcal/personne/jour)'].tolist()
positions = [(proportions-150, i-0.43) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=150,
sizey=150,
layer="above",
)
)
# Format the text to be displayed directly on the bars
fig.update_traces(texttemplate='%{text:,.0f}', textposition='outside')
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", showgrid=False)
fig.show()
fig.write_image("src/main/extracted_data/10.svg")
3.11. Exemple de la Thaïlande pour le Manioc¶
#Exemple de la Thaïlande pour le Manioc
#création d'un dataframe avec uniquement la Thaïlande
dispo_alimentaire_thailande = dispo_alimentaire[dispo_alimentaire['Zone'] == 'Thaïlande']
#Calcul de la sous nutrition en Thaïlande
sous_nutrition_thailande = sous_nutrition_2017[sous_nutrition_2017['Zone'] == 'Thaïlande']
print(sous_nutrition_thailande)
Zone Année Sous_nutrition 1114 Thaïlande 2016-2018 6,200,000.00
# Calculate the sum of 'Population' and 'Sous_nutrition'
sous_nutrition_thailande_sum = sous_nutrition_thailande["Sous_nutrition"].sum()
population_thailande = population_2017[population_2017['Zone'] == 'Thaïlande']['Population'].sum()
# Calculate the rates
sous_nutrition_rate = sous_nutrition_thailande_sum / population_thailande * 100
sufficient_nutrition_rate = 100 - sous_nutrition_rate
# Create a new DataFrame for the pie chart
df_pie = pd.DataFrame(
{
"Nutrition": ["Undernourished", "Sufficient"],
"Rate": [sous_nutrition_rate, sufficient_nutrition_rate],
}
)
# Create the pie chart
fig = px.pie(
df_pie,
values="Rate",
names="Nutrition",
title="Thailande Nutrition Status in 2017",
hole=0.3,
color_discrete_sequence=["blue", "red"],
)
fig.update_traces(textinfo="percent+label", pull=[0.1, 0], rotation=105)
fig.update_layout(
width=800,
height=600,
annotations=[dict(text="Total Pop:<br> 69 Million", showarrow=False)],
showlegend=False,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
fig.show()
fig.write_image("src/main/extracted_data/11.svg")
# On calcule la proportion exportée en fonction de la proportion
# disponible intérieurement pour chaque produit
dispo_alimentaire_thailande['Exportation (%)'] = dispo_alimentaire_thailande['Exportations - Quantité'] / dispo_alimentaire_thailande['Production'] * 100
dispo_alimentaire_thailande[dispo_alimentaire_thailande["Produit"] == "Manioc"]
| Zone | Produit | Origine | Aliments pour animaux | Autres Utilisations | Disponibilité alimentaire (Kcal/personne/jour) | Disponibilité alimentaire en quantité (kg/personne/an) | Disponibilité de matière grasse en quantité (g/personne/jour) | Disponibilité de protéines en quantité (g/personne/jour) | Disponibilité intérieure | Exportations - Quantité | Importations - Quantité | Nourriture | Pertes | Production | Semences | Traitement | Variation de stock | Population | Disponibilité alimentaire en million (Kcal/jour) | Exportation (%) | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 13620 | Thaïlande | Manioc | vegetale | 1,800,000,000.00 | 2,081,000,000.00 | 40.00 | 13.00 | 0.05 | 0.14 | 6,264,000,000.00 | 25,214,000,000.00 | 1,250,000,000.00 | 871,000,000.00 | 1,511,000,000.00 | 30,228,000,000.00 | 0.00 | 0.00 | 0.00 | 69,209,810.00 | 2,768,392,400.00 | 83.41 |
# Filter the data for the product "Manioc"
manioc_data = dispo_alimentaire_thailande[
dispo_alimentaire_thailande["Produit"] == "Manioc"
]
# Calculate exportation and consumption proportions
exportation = manioc_data["Exportation (%)"].mean() / 100
consumption = 1 - exportation
total_manioc_prod = manioc_data["Production"].mean()
# Create a pie chart
fig = go.Figure(
data=[
go.Pie(
labels=["Exportation", "Consumption"],
values=[exportation, consumption],
hole=0.3,
marker=dict(colors=["Green", "gray"]),
)
]
)
fig.update_traces(textinfo="percent+label", pull=[0, 0.1], rotation=-55)
fig.update_layout(
title_text="Exportation of Manioc in Thailand",
width=800,
height=600,
showlegend=False,
annotations=[
dict(
text=f"Total Manioc:<br>{total_manioc_prod/1_000_000_000:,.0f} Billion kg",
showarrow=False,
)
],
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=16),
)
fig.show()
fig.write_image("src/main/extracted_data/12.svg")
manioc_export = dispo_alimentaire_thailande[dispo_alimentaire_thailande["Produit"] == "Manioc"]['Exportations - Quantité'].sum()
manioc_export_feed = manioc_export * 1250 / (2250 * 365)
print("{:,.2f} million".format(manioc_export_feed))
38,377,473.36 million
# Data
sous_nutrition_thailande_sum
capacity = manioc_export_feed
sous_nutrition_thailande_percent = 100
capacity_percent = capacity / sous_nutrition_thailande_sum * 100
# Create a bar chart using Plotly
fig = go.Figure(
data=[
go.Bar(
name="Population",
x=["Population"],
y=[sous_nutrition_thailande_sum],
marker_color="red",
text=[f"{sous_nutrition_thailande_percent:.0f}%"],
textposition="outside",
),
go.Bar(
name="Capacity",
x=["Capacity"],
y=[capacity],
marker_color="green",
text=[f"{capacity_percent:.0f}%"],
textposition="outside",
),
]
)
# Update the layout
fig.update_layout(
title="Under Nurrished Population vs Feeding Capacity by Manioc in Thailand",
yaxis_title="Population",
barmode="group",
showlegend=False,
width=800,
height=600,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# Add annotations one by one
fig.add_annotation(
x="Population",
y=sous_nutrition_thailande_sum / 2,
text=f"{sous_nutrition_thailande_sum/1_000_000:.1f} Million",
showarrow=False,
font=dict(color="white", size=30),
)
fig.add_annotation(
x="Capacity",
y=capacity / 2,
text=f"{capacity/1_000_000:.1f} Million",
showarrow=False,
font=dict(color="white", size=30),
)
# Show the figure
fig.show()
fig.write_image("src/main/extracted_data/13.svg")
4. Analyse complémentaires¶
4.1. Top 10 des pays les plus producteurs¶
columns_to_sum = ['Exportations - Quantité', 'Importations - Quantité', 'Production']
dispo_alimentaire.groupby('Zone')[columns_to_sum].sum().sort_values(by='Production', ascending=False).head(10)
| Exportations - Quantité | Importations - Quantité | Production | |
|---|---|---|---|
| Zone | |||
| Chine, continentale | 36,060,000,000.00 | 156,246,000,000.00 | 1,930,913,000,000.00 |
| Brésil | 126,552,000,000.00 | 16,817,000,000.00 | 1,143,605,000,000.00 |
| Inde | 40,807,000,000.00 | 18,954,000,000.00 | 1,126,270,000,000.00 |
| États-Unis d'Amérique | 163,524,000,000.00 | 81,887,000,000.00 | 894,668,000,000.00 |
| Fédération de Russie | 26,777,000,000.00 | 30,449,000,000.00 | 263,296,000,000.00 |
| Indonésie | 31,912,000,000.00 | 23,466,000,000.00 | 238,559,000,000.00 |
| Thaïlande | 50,430,000,000.00 | 11,335,000,000.00 | 201,764,000,000.00 |
| Nigéria | 748,000,000.00 | 14,510,000,000.00 | 179,631,000,000.00 |
| France | 65,945,000,000.00 | 33,769,000,000.00 | 178,136,000,000.00 |
| Argentine | 52,333,000,000.00 | 1,212,000,000.00 | 176,124,000,000.00 |
# Group and sort the data
top_production = dispo_alimentaire.groupby('Zone')[columns_to_sum].sum().sort_values(by='Production', ascending=False).head(10)
# top_production.set_index('Zone', inplace=True)
# Create the Plotly bar chart
fig = go.Figure(go.Bar(
x=top_production['Production'],
y=top_production.index,
orientation='h',
marker=dict(
color=top_production['Production'],
# colorscale='Blues', # Change to a continuous color scale
colorscale=["rgb(229,229,255)", "rgb(0,0,255)"]
# reversescale=True, # Add this line to reverse the color scale
# colorbar=dict(
# title='Kcal/personne/jour',
# tickvals=top_production['Production']
# )
),
text=top_production['Production'] / 1_000_000_000_000,
))
fig.update_layout(
title='Top 10 Pays avec le plus de Production',
xaxis_title='Production (€)',
yaxis_title='',
yaxis=dict(autorange='reversed'), # Invert the y-axis to display the country with the highest number at the top
template='plotly_white',
width= 1500,
height= 700,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/cn.svg",
"https://flagicons.lipis.dev/flags/4x3/br.svg",
"https://flagicons.lipis.dev/flags/4x3/in.svg",
"https://flagicons.lipis.dev/flags/4x3/us.svg",
"https://flagicons.lipis.dev/flags/4x3/ru.svg",
"https://flagicons.lipis.dev/flags/4x3/id.svg",
"https://flagicons.lipis.dev/flags/4x3/th.svg",
"https://flagicons.lipis.dev/flags/4x3/ng.svg",
"https://flagicons.lipis.dev/flags/4x3/fr.svg",
"https://flagicons.lipis.dev/flags/4x3/ar.svg"
]
# Positions of the images
proportions = top_production['Production'].tolist()
positions = [(proportions-100_000_000_000, i-0.43) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=100_000_000_000,
sizey=100_000_000_000,
layer="above",
)
)
# Format the text to be displayed directly on the bars
fig.update_traces(texttemplate='€%{text:,.2f}T', textposition='outside')
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", showgrid=False)
fig.show()
fig.write_image("src/main/extracted_data/14.svg")
4.2. Top 10 pays dont la production est la plus faible¶
# Group and sort the data
least_production = dispo_alimentaire.groupby('Zone')[columns_to_sum].sum().sort_values(by='Production', ascending=True).head(10)
# least_production.set_index('Zone', inplace=True)
# Create the Plotly bar chart
fig = go.Figure(go.Bar(
x=least_production['Production'],
y=least_production.index,
orientation='h',
marker=dict(
color=least_production['Production'],
colorscale='Reds', # Change to a continuous color scale
# colorscale=["rgb(229,229,255)", "rgb(0,0,255)"]
# reversescale=True, # Add this line to reverse the color scale
# colorbar=dict(
# title='Kcal/personne/jour',
# tickvals=least_production['Production']
# )
),
text=least_production['Production'] / 1_000_000,
))
fig.update_layout(
title='Top 10 Pays avec the least de Production',
xaxis_title='Production (€)',
yaxis_title='',
yaxis=dict(autorange='reversed'), # Invert the y-axis to display the country with the highest number at the top
template='plotly_white',
width= 1500,
height= 700,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/bm.svg",
"https://flagicons.lipis.dev/flags/4x3/mo.svg",
"https://flagicons.lipis.dev/flags/4x3/ag.svg",
"https://flagicons.lipis.dev/flags/4x3/kn.svg",
"https://flagicons.lipis.dev/flags/4x3/gd.svg",
"https://flagicons.lipis.dev/flags/4x3/bn.svg",
"https://flagicons.lipis.dev/flags/4x3/lc.svg",
"https://flagicons.lipis.dev/flags/4x3/dj.svg",
"https://flagicons.lipis.dev/flags/4x3/nc.svg",
"https://flagicons.lipis.dev/flags/4x3/dm.svg"
]
# Positions of the images
proportions = least_production['Production'].tolist()
positions = [(proportions-6_000_000, i-0.43) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=6_000_000,
sizey=6_000_000,
layer="above",
)
)
# Format the text to be displayed directly on the bars
fig.update_traces(texttemplate='€%{text:,.0f}M', textposition='outside')
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", showgrid=False)
fig.show()
fig.write_image("src/main/extracted_data/15.svg")
4.3. 10 premiers pays exportateurs¶
# Group and sort the data
top_export = dispo_alimentaire.groupby('Zone')[columns_to_sum].sum().sort_values(by='Exportations - Quantité', ascending=False).head(10)
# top_export.set_index('Zone', inplace=True)
# Create the Plotly bar chart
fig = go.Figure(go.Bar(
x=top_export['Exportations - Quantité'],
y=top_export.index,
orientation='h',
marker=dict(
color=top_export['Exportations - Quantité'],
# colorscale='Blues', # Change to a continuous color scale
colorscale=["rgb(145,240,134)", "rgb(2,35,28)"]
# reversescale=True, # Add this line to reverse the color scale
# colorbar=dict(
# title='Kcal/personne/jour',
# tickvals=top_export['Exportations - Quantité']
# )
),
text=top_export['Exportations - Quantité'] / 1_000_000_000,
))
fig.update_layout(
title='Top 10 Pays avec le plus de Exportations - Quantité',
xaxis_title='Exportations - Quantité',
yaxis_title='',
yaxis=dict(autorange='reversed'), # Invert the y-axis to display the country with the highest number at the top
template='plotly_white',
width= 1500,
height= 800,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/us.svg",
"https://flagicons.lipis.dev/flags/4x3/br.svg",
"https://flagicons.lipis.dev/flags/4x3/fr.svg",
"https://flagicons.lipis.dev/flags/4x3/de.svg",
"https://flagicons.lipis.dev/flags/4x3/ca.svg",
"https://flagicons.lipis.dev/flags/4x3/ar.svg",
"https://flagicons.lipis.dev/flags/4x3/nl.svg",
"https://flagicons.lipis.dev/flags/4x3/th.svg",
"https://flagicons.lipis.dev/flags/4x3/au.svg",
"https://flagicons.lipis.dev/flags/4x3/in.svg"
]
# Positions of the images
proportions = top_export['Exportations - Quantité'].tolist()
positions = [(proportions-10_000_000_000, i-0.43) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=10_000_000_000,
sizey=10_000_000_000,
layer="above",
)
)
# Format the text to be displayed directly on the bars
fig.update_traces(texttemplate='%{text:,.2f}B', textposition='outside')
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", showgrid=False)
fig.show()
fig.write_image("src/main/extracted_data/16.svg")
4.4. Les 10 premiers pays importateurs¶
# Group and sort the data
top_import = dispo_alimentaire.groupby('Zone')[columns_to_sum].sum().sort_values(by='Importations - Quantité', ascending=False).head(10)
# top_import.set_index('Zone', inplace=True)
# Create the Plotly bar chart
fig = go.Figure(go.Bar(
x=top_import['Importations - Quantité'],
y=top_import.index,
orientation='h',
marker=dict(
color=top_import['Importations - Quantité'],
colorscale='ylorbr', # Change to a continuous color scale
# colorscale=["rgb(145,240,134)", "rgb(2,35,28)"]
# reversescale=True, # Add this line to reverse the color scale
# colorbar=dict(
# title='Kcal/personne/jour',
# tickvals=top_import['Importations - Quantité']
# )
),
text=top_import['Importations - Quantité'] / 1_000_000_000,
))
fig.update_layout(
title='Top 10 Pays avec le plus de Importations - Quantité',
xaxis_title='Importations - Quantité',
yaxis_title='',
yaxis=dict(autorange='reversed'), # Invert the y-axis to display the country with the highest number at the top
template='plotly_white',
width= 1500,
height= 800,
paper_bgcolor="rgba(0,0,0,0)", # make the paper background transparent
plot_bgcolor="rgba(0,0,0,0)", # make the plot background transparent
font=dict(color="white", size=14),
)
# URLs of the images
image_urls = [
"https://flagicons.lipis.dev/flags/4x3/cn.svg",
"https://flagicons.lipis.dev/flags/4x3/us.svg",
"https://flagicons.lipis.dev/flags/4x3/de.svg",
"https://flagicons.lipis.dev/flags/4x3/jp.svg",
"https://flagicons.lipis.dev/flags/4x3/nl.svg",
"https://flagicons.lipis.dev/flags/4x3/it.svg",
"https://flagicons.lipis.dev/flags/4x3/be.svg",
"https://flagicons.lipis.dev/flags/4x3/fr.svg",
"https://flagicons.lipis.dev/flags/4x3/es.svg",
"https://flagicons.lipis.dev/flags/4x3/mx.svg"
]
# Positions of the images
proportions = top_import['Importations - Quantité'].tolist()
positions = [(proportions-10_000_000_000, i-0.45) for i, proportions in enumerate(proportions)]
for url, (x, y) in zip(image_urls, positions):
fig.add_layout_image(
dict(
source=url,
xref="x",
yref="y",
x=x,
y=y,
sizex=10_000_000_000,
sizey=10_000_000_000,
layer="above",
)
)
# Format the text to be displayed directly on the bars
fig.update_traces(texttemplate='%{text:,.2f}B', textposition='outside')
fig.update_xaxes(showline=True, linewidth=1, linecolor="white", showgrid=False)
fig.show()
fig.write_image("src/main/extracted_data/17.svg")